package com.ruoyi.app.service;

import com.ruoyi.app.utils.RandomUtil;
import com.ruoyi.business.domain.JtAppUser;
import com.ruoyi.business.service.IJtAppUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.*;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author Alan Zhang
 * @Date 2025/3/31 16:24
 */
@Component
public class AppRegisterService {
    @Autowired
    private IJtAppUserService userService;

    @Autowired
    private PasswordService passwordService;

    /**
     * 注册
     */
    public String register(JtAppUser user)
    {
        String msg = "", loginName = user.getPhoneNumber(), password = user.getPassword();

       if(user.getCountryCode() == null){
           msg = "国家码不能为空！";
       }
       else if (StringUtils.isEmpty(loginName))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
                || loginName.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (!userService.checkPhoneUnique(user))
        {
            msg = "用户'" + loginName + "'失败，注册账号已存在";
        }
        else if(StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)){

           msg = "邮件'" + user.getEmail() + "'失败，已存在";
        }
        else
        {
            if(StringUtils.isEmpty(user.getUserName())){
                user.setUserName("jt_"+RandomUtil.genBuyerCode());
            }
            //推广码
            user.setPromotionCode(RandomUtil.genPromotionCode());
            //修改密码时间
            user.setPwdUpdateDate(DateUtils.getNowDate());
            user.setSalt(ShiroUtils.randomSalt());
            user.setPassword(passwordService.encryptPassword(loginName, password, user.getSalt()));
            boolean regFlag = userService.registerUser(user);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }
}
